package com.qunar.train.mock.config;

import com.google.common.io.Files;

import com.qunar.train.mock.util.AegisLog;
import com.qunar.train.mock.util.ConfigHandle;

import org.springframework.util.StringUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.nio.charset.Charset;

/**
 * Author:zhangqianqian.zhang Date:2018/9/18
 */
public class ChangeQconfigEnv {

    public ChangeQconfigEnv() {
    }

    public static void changeQconfigEnv(Boolean local) {
        if (local) {
            setToLocal();
        } else {
            setToOnline();
        }

    }

    private static void setToOnline() {
        setStatus("\n#pbservice.host=#", "\npbservice.host=#");
        AegisLog.log("The Qconfig System is set to online");
    }

    private static void setToLocal() {
        setStatus("\npbservice.host=#", "\n#pbservice.host=#");
        AegisLog.log("The Qconfig System is set to local");
    }

    private static void setStatus(String newValue, String oldValue) {
        try {
            String filePath = "qunar-env.properties";
            File file = ConfigHandle.loadConfigToFile(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException("file not found");
            }

            String oldContent = Files.toString(file, Charset.forName("UTF-8"));
            String content = StringUtils.replace(oldContent, oldValue, newValue);

            FileWriter fileWritter = new FileWriter(file.getPath(), false);
            BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            bufferWritter.write(content);
            bufferWritter.flush();
            bufferWritter.close();

        } catch (Exception var11) {
            AegisLog.error(var11);
        }
    }

}
